<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { querySummary, deleteWaterReport } from "@/api/machineClass";
import { reactive, ref, toRefs, onMounted, getCurrentInstance, markRaw } from "vue";
import icon_na from "@/assets/svg/machine/icon_na.svg?component";
import icon_warning from "@/assets/svg/machine/icon_warning.svg?component";
import waterTestQuailty from "@/views/machine/operation/havcWaterTest/components/overView/components/waterTestQuailty.vue";
import { PxMessage, PxMessageBox } from "px-ui";
const iconComList = {
  icon_na: markRaw(icon_na),
  icon_warning: markRaw(icon_warning)
};

const { proxy }: any = getCurrentInstance();
const props = defineProps({
  activeName: {
    type: String,
    default: () => ""
  }
});

const state = reactive<any>({
  classNameArr: [],
  queryParams: {
    subsystem: props.activeName,
    pageNum: 1,
    pageSize: 10
  },
  querySpcParams: {},
  total: 0,
  tableData: [],
  selectIds: []
});

const { selectIds, queryParams, classNameArr, total, tableData } = toRefs(state);
const dateRange = ref([]);
const detectResultData = ref([
  {
    label: "合格",
    value: "1"
  },
  {
    label: "不合格",
    value: "0"
  }
]);
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 0, 0, 0)];

//查字典
const systemList = ref();
const queryDic = async () => {
  systemList.value = await queryDictData({ typeCode: "factoryArea" });
};
onMounted(() => {
  queryTable();
  queryDic();
});

// 表格多选框选中
const selectionChange = (val: any) => {
  // selectIds.value = [];
  // val.forEach((item: any) => {
  //   if (item.checklistId) {
  //     selectIds.value.push(item.checklistId);
  //   }
  // });
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.sampleDate) {
      selectIds.value.push(item.sampleDate);
    }
  });
};

const summaryTitle = ref(["加药日期", "MCHW", "LCHW", "HW", "HHW", "CW", "PCW"]);
const originTitle = ref(["问题描述", "不良影响或风险", "改善措施", "完成时间", "完成状态"]);
interface subRow {
  problemDesc: "";
  risk: "";
  improvement: "";
  completionTime: "";
  completionStatus: "";
}

const resolveArr = (arr: any) => {
  let data = arr.map((row: any, i) => {
    let list = [];
    for (let key in row) {
      list.push(row[key]);
    }
    return list;
  });
  return data;
};
// 查询
const queryTable = async () => {
  const params = proxy.addDateRange(queryParams.value, dateRange.value, "reportStart", "reportEnd");
  const data = await querySummary(params);
  let resData = data.data;
  console.log(resData);
  resData.forEach((item: any, index) => {
    item.summary.forEach((el: any, ind) => {
      el.index = summaryTitle.value.indexOf(el.systemName);
      item[el.systemName] = el.detectResultSummary === "1" ? true : false;
    });
    item.summary.sort((a, b) => a.index - b.index); // 按tabs顺序排列
    let arr = item.summary.map((el: any, ind) => {
      return {
        problemDesc: el.problemDesc,
        risk: el.risk,
        improvement: el.improvement,
        completionTime: el.completionTime,
        completionStatus: el.completionStatus
      };
    });
    let transData = resolveArr(arr);
    console.log(transData);
    item.summary = transData[0].map((col, i) => {
      return [
        originTitle.value[i],
        ...transData.map((row: any) => {
          return row[i];
        })
      ];
    });
  });
  console.log(resData);
  tableData.value = resData;
  total.value = data?.total;
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = [];
  queryParams.value = {
    subsystem: props.activeName,
    pageNum: 1,
    pageSize: 10
  };
  queryTable();
};
//删除
const handleDelete = () => {
  if (!selectIds.value.length) {
    PxMessage.warning("请至少选择一条数据");
    return;
  }

  PxMessageBox.confirm("是否确认删除【" + selectIds.value + "】记录？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res: any = await deleteWaterReport(selectIds.value);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    })
    .catch(() => {});
};
</script>

<template>
  <div class="tabsContent">
    <div class="tableCon">
      <px-form ref="formRef" class="custom-form-ui inspection-form" :model="queryParams" label-position="right" label-width="120px">
        <px-form-item label="检测结果">
          <px-select v-model="queryParams.detectResult" filterable clearable placeholder="请选择检测结果">
            <px-option v-for="item in detectResultData" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="报告日期" style="width: 430px">
          <px-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </px-form-item>
        <div class="query-btn-group">
          <px-button type="primary" @click="queryTable">查询</px-button>
          <px-button @click="resetTable">重置</px-button>
        </div>
      </px-form>
      <div class="mgBottom16">
        <px-button v-has="'MACHINE_OPERATE_HAVCWATERTEST_DELETE'" type="danger" plain icon="Delete" @click="handleDelete">删除</px-button>
      </div>
      <px-scrollbar>
        <px-table
          :data="tableData"
          default-expand-all
          class="inspection-table"
          height="calc(100vh -400px)"
          border
          @selection-change="selectionChange"
        >
          <px-table-column label="" width="48" type="selection" />
          <px-table-column type="expand">
            <template #default="scope">
              <px-table class="expand-table" :data="scope.row.summary" border :show-header="false">
                <px-table-column label="" width="96" />
                <px-table-column v-for="(item, index) in summaryTitle" :key="index" :label="item">
                  <template #default="scope">
                    <div>
                      {{ scope.row[index] || "NA" }}
                    </div>
                  </template>
                </px-table-column>
              </px-table>
            </template>
          </px-table-column>
          <px-table-column label="检测日期" prop="sampleDate" />
          <px-table-column label="MCHW">
            <template #default="scope">
              <component :is="iconComList.icon_warning" v-if="!scope.row.MCHW" class="content-icon" />
              <component :is="iconComList.icon_na" v-else class="content-icon" />
            </template>
          </px-table-column>
          <px-table-column label="LCHW">
            <template #default="scope">
              <component :is="iconComList.icon_warning" v-if="!scope.row.LCHW" class="content-icon" />
              <component :is="iconComList.icon_na" v-else class="content-icon" />
            </template>
          </px-table-column>
          <px-table-column label="HW">
            <template #default="scope">
              <component :is="iconComList.icon_warning" v-if="!scope.row.HW" class="content-icon" />
              <component :is="iconComList.icon_na" v-else class="content-icon" />
            </template>
          </px-table-column>
          <px-table-column label="HHW">
            <template #default="scope">
              <component :is="iconComList.icon_warning" v-if="!scope.row.HHW" class="content-icon" />
              <component :is="iconComList.icon_na" v-else class="content-icon" />
            </template>
          </px-table-column>
          <px-table-column label="CW">
            <template #default="scope">
              <component :is="iconComList.icon_warning" v-if="!scope.row.CW" class="content-icon" />
              <component :is="iconComList.icon_na" v-else class="content-icon" />
            </template>
          </px-table-column>
          <px-table-column label="PCW">
            <template #default="scope">
              <component :is="iconComList.icon_warning" v-if="!scope.row.PCW" class="content-icon" />
              <component :is="iconComList.icon_na" v-else class="content-icon" />
            </template>
          </px-table-column>
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
      </px-scrollbar>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspection-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <div class="bg-grey" />
    <div class="spcCon">
      <waterTestQuailty />
    </div>
  </div>
</template>

<style lang="scss" scoped>
$colorTotal: var(--px-color-primary);

.tabsContent {
  margin-top: 10px;

  .bg-grey {
    width: 100%;
    height: 16px;
    background-color: #eff1f4;
  }

  .tableCon {
    padding: 0 20px 20px;

    .custom-form-ui {
      display: flex;

      .query-btn-group {
        display: flex;
        margin-bottom: 16px;
      }
    }

    :deep(.px-table__expanded-cell) {
      padding: 0;
      border: none;
    }

    :deep(.expand-table .px-table__cell) {
      background-color: #f7f7f7;
      border-top: none;
      border-bottom: none;
    }

    .content-icon {
      width: 30px;
      height: 30px;
    }
  }

  .bgDom {
    height: 16px;
    background-color: #f0f2f5;
  }

  .mgBottom16 {
    margin-bottom: 16px;
  }
}

.spcCon {
  width: 100%;
  min-width: 1300px;
  padding: 16px 24px;
}
</style>
